<template>
  <div>
    <div class="formBox">
      <t-form
        v-show="!isFold"
        ref="form"
        :rules="FORM_RULES"
        :data="formData"
        :layout="'inline'"
        scroll-to-first-error="smooth"
        :class="isFold ? '' : 'paddingBottom'"
        labelAlign="right"
      >
        <t-form-item
          label="手机号码"
          name="mobilephonenum"
          :label-width="90"
          requiredMark
        >
          <t-input
            placeholder="请输入手机号码"
            v-model="formData.mobilephonenum"
            style="width: 165px"
          />
        </t-form-item>
        <t-form-item
          label="外呼次数"
          name="calloutnum"
          :label-width="90"
          requiredMark
        >
          <t-input
            placeholder="请输入手机号码"
            v-model="formData.mincall"
            @change="onMinCallChange"
            type="number"
            style="width: 70px"
          />
          <span style="width: 20px; text-align: center">~</span>
          <t-input
            placeholder="请输入手机号码"
            v-model="formData.maxcall"
            @change="onMaxCallChange"
            type="number"
            style="width: 70px"
          />
        </t-form-item>
        <t-form-item
          label="外呼状态"
          name="calloutstatus"
          :label-width="90"
          requiredMark
        >
          <t-select
            placeholder="请选择外呼状态"
            v-model="formData.calloutstatus"
            @change="onPlatformChange"
            :options="platformOptions"
            filterable
            style="width: 165px"
          ></t-select>
        </t-form-item>
        <t-form-item
          label="意向标签"
          name="intentionlabsls"
          :label-width="90"
          requiredMark
        >
          <t-select
            placeholder="请选择意向标签"
            v-model="formData.intentionlabsls"
            @change="onPlatformChange"
            :options="platformOptions"
            filterable
            style="width: 165px"
          ></t-select>
        </t-form-item>
        <t-form-item
          label="自定义标签"
          name="customizationlabsls"
          :label-width="90"
          requiredMark
        >
          <t-select
            placeholder="请选择自定义标签"
            v-model="formData.customizationlabsls"
            @change="onPlatformChange"
            :options="platformOptions"
            filterable
            style="width: 165px"
          ></t-select>
        </t-form-item>
        <t-form-item
          label="通话时长"
          name="callduration"
          :label-width="90"
          requiredMark
        >
          <t-select
            placeholder="请选择通话时长"
            v-model="formData.callduration"
            @change="onPlatformChange"
            :options="platformOptions"
            filterable
            style="width: 165px"
          ></t-select>
        </t-form-item>
        <t-form-item
          label="对话轮次"
          name="dialoguerounds"
          :label-width="90"
          requiredMark
        >
          <t-select
            placeholder="请选择对话轮次"
            v-model="formData.dialoguerounds"
            @change="onPlatformChange"
            :options="platformOptions"
            filterable
            style="width: 165px"
          ></t-select>
        </t-form-item>
        <t-form-item
          label="运营商"
          name="operator"
          :label-width="90"
          requiredMark
        >
          <t-select
            placeholder="请选择运营商"
            v-model="formData.operator"
            @change="onPlatformChange"
            :options="platformOptions"
            filterable
            style="width: 165px"
          ></t-select>
        </t-form-item>
        <t-form-item
          label="归属地（省）"
          name="provinceaff"
          :label-width="90"
          requiredMark
        >
          <t-select
            placeholder="请选择归属地（省）"
            v-model="formData.provinceaff"
            @change="onPlatformChange"
            :options="platformOptions"
            filterable
            style="width: 170px"
          ></t-select>
        </t-form-item>
        <t-form-item
          label="归属地（市）"
          name="cityaff"
          :label-width="90"
          requiredMark
        >
          <t-select
            placeholder="请选择归属地（市）"
            v-model="formData.cityaff"
            @change="onPlatformChange"
            :options="platformOptions"
            filterable
            style="width: 165px"
          ></t-select>
        </t-form-item>

        <t-form-item
          label="通话时间"
          name="timescope"
          :label-width="90"
          requiredMark
        >
          <t-date-range-picker
            v-model="calltime"
            :presets="presets"
            :disableDate="disDate"
            style="width: 295px"
          />
        </t-form-item>
        <t-form-item
          label="导入时间"
          name="timescope"
          :label-width="90"
          requiredMark
        >
          <t-date-range-picker
            v-model="importingtime"
            :presets="presets"
            :disableDate="disDate"
            style="width: 295px"
          />
        </t-form-item>
        <!-- <dk-button>测试</dk-button> -->
        <t-form-item class="formHandleBox" v-if="!isFold" :label-width="0">
          <t-space size="small" style="gap: 10px; width: 60px">
            <dk-button @click="handleQuery">查询</dk-button>
            <!-- <dk-button @click="handleReset" type="outlinePrimary">刷新</dk-button> -->
          </t-space>
        </t-form-item>
      </t-form>
      <!-- 展开 -->
      <!-- <div class="upArrow" v-show="isFold">
					<icon-svg @click="handleArrow" :name="'icon-arrowTD'" class-name="arrowTD-svg-icon" :style="isFold === true ? '' : 'transform: rotate(180deg)'"></icon-svg>
				</div> -->
      <!-- 拖拽排序涉及到 data 的变更，相对比较慎重，因此仅支持受控用法 -->
      <dk-divider style="margin: 20px 0"></dk-divider>
      <div class="topbuttons">
        <t-radio-group
          v-model="reserveSelectedRowOnPaginate"
          variant="default-filled"
        >
          <t-radio-button :value="true">跨分页选中</t-radio-button>
          <t-radio-button :value="false">当前页选中</t-radio-button>
        </t-radio-group>
        <dk-button>导出通话记录</dk-button>
        <dk-button>未接重呼</dk-button>
        <dk-button>接听重呼</dk-button>
        <dk-button>加入黑名单</dk-button>
      </div>

      <t-table
        row-key="index"
        :pagination="pagination"
        :columns="columns"
        :data="data"
        drag-sort="col"
        lazy-load
        @drag-sort="onDragSort"
        :editable-row-keys="editableRowKeys"
        :reserve-selected-row-on-paginate="reserveSelectedRowOnPaginate"
        :selected-row-keys="selectedRowKeys"
        @select-change="rehandleSelectChange"
      >
      </t-table>
    </div>
  </div>
  <calldetails :isshow="isshow" @close="close"></calldetails>
</template>

<script setup lang="jsx">
import { ref,reactive } from 'vue';
import calldetails from "./calldetails.vue";
const editableRowKeys = ref(['1'])
const reserveSelectedRowOnPaginate = ref(true);//选择当页全选 所有全选
const selectedRowKeys = ref([]); //选中行数组
const rehandleSelectChange = (value, ctx) => {//全选事件
	selectedRowKeys.value = value;
	console.log(value, ctx);
};
// 分页
const pagination = reactive({
//   current: 2,
//   pageSize: 5,
  defaultCurrent: 2,
  defaultPageSize: 5,
  total: 100,
//   showJumper: true,
})
const isshow = ref(false);
// 通话详情按钮
const onEdit = (e) => {
    // 切换按钮 比如改变一个状态后 出现新的按钮 此按钮消失
//   const { id } = e.currentTarget.dataset;
//   if (!editableRowKeys.value.includes(id)) {
//     editableRowKeys.value.push(id);
//   }
isshow.value = true;
console.log('通话详情');
};
const close = (val) => {
    isshow.value = val;
}
// 表格数据
const data = [];
for (let i = 0; i < 100; i++) {
  data.push({
    index: i + 1,
    applicant: ['贾明', '张三', '王芳'][i % 3],
    mobilephonenum: ['13333672892', '13333672892', '13333672892'][i % 3],
    categories: i % 3,
    channel: ['电子签署', '纸质签署', '纸质签署'][i % 3],
    detail: {
      email: ['w.cezkdudy@lhll.au', 'r.nmgw@peurezgn.sl', 'p.cumx@rampblpa.ru'][i % 3],
    },
    matters: ['宣传物料制作费用', 'algolia 服务报销', '相关周边制作费', '激励奖品快递费'][i % 4],
    time: [2, 3, 1, 4][i % 4],
    createTime: ['2022-01-01', '2022-02-01', '2022-03-01', '2022-04-01', '2022-05-01'][i % 4],
  });
}
// 表格columns列
const initialColumns = [
	{
		colKey: 'row-select',
		type: 'multiple',
		// 禁用行选中方式一：使用 disabled 禁用行（示例代码有效，勿删）。disabled 参数：{row: RowData; rowIndex: number })
		// 这种方式禁用行选中，当前行会添加行类名 t-table__row--disabled，禁用行文字变灰
		// disabled: ({ rowIndex }) => rowIndex === 1 || rowIndex === 3,

		// 禁用行选中方式二：使用 checkProps 禁用行（示例代码有效，勿删）
		// 这种方式禁用行选中，行文本不会变灰
		// checkProps: ({ rowIndex }) => ({ disabled: rowIndex % 2 !== 0 }),
		width: 50
	},
//   { colKey: 'index', title: '序号', fixed: 'left' },
  { colKey: 'applicant', title: '编号', width: '100',},
  { colKey: 'mobilephonenum', title: '手机号码', width: '120' },
  { colKey: 'calloutstatus', title: '外呼状态', width: '120' },
  { colKey: 'customizationlabsls', title: '自定义标签', ellipsis: true },
  { colKey: 'calloutnum', title: '外呼次数', ellipsis: true },
  { colKey: 'calltime', title: '通话时长', ellipsis: true },
  { colKey: 'dialoguerounds', title: '对话轮次', ellipsis: true },
  { colKey: 'dialoguevariables', title: '对话变量', ellipsis: true },//有就展示没有就不展示
  { colKey: 'startcallTime', title: '开始通话时间' },
  { colKey: 'endcallTime', title: '结束通话时间' },
  { colKey: 'createTime', title: '导入时间' },
  { colKey: 'operator', title: '运营商', ellipsis: true },
  { colKey: 'provinceaff', title: '归属地（省）', ellipsis: true },
  { colKey: 'cityaff', title: '归属地（市）', ellipsis: true },
  { 
    colKey: 'operation',
    title: '操作',
    fixed: 'right',
    width: '120',
    cell: (h, { row }) => {
      const editable = editableRowKeys.value.includes(row.key);
      return (
        <div class="table-operations">
          {!editable && (
            <dk-button theme="primary" hover="color" data-id={row.key} onClick={onEdit}>
              通话详情
            </dk-button>
          )}
          {/* {editable && (
            <t-link theme="primary" hover="color" data-id={row.key} onClick={onSave}>
              保存
            </t-link>
          )}
          {editable && (
            <t-link theme="primary" hover="color" data-id={row.key} onClick={onCancel}>
              取消
            </t-link>
          )} */}
        </div>
      );
    }
  },
];
const columns = ref(initialColumns);

// 
// currentData is going to be deprecated
const onDragSort = ({ currentIndex, targetIndex, current, target, data, newData, e, sort }) => {
  console.log('交换行', currentIndex, targetIndex, current, target, data, newData, e, sort);
  if (sort === 'col') {
    columns.value = newData;
  }
};



// form 表单
const formData = reactive({
	mobilephonenum: '', //电话号码
	calloutnum: [], //外呼次数区间
	mincall: '', //外呼次数区间
	maxcall: '', //外呼次数区间
	provinceaff: '', //归属地（省）
	cityaff: '', //归属地（市）
	categories: '', //类别
	operator: '', //运营商
    calloutstatus:'',//外呼状态 多选
    intentionlabsls:'',//意向标签 多选
    customizationlabsls:'',//自定义标签 多选
    callduration:'',//通话时长 多选
    dialoguerounds:'',//对话轮次 多选
});
// 通话时间
const calltime = ref([]);
// 导入时间
const importingtime = ref([]);
// 获取当前日期
const now = new Date();
// 计算本周一的时间
const startOfWeek = new Date(now);
const dayOfWeek = now.getDay(); // 获取当前是星期几，0 表示星期天
const diff = dayOfWeek === 0 ? 6 : dayOfWeek - 1; // 如果是星期天，回退到前一个星期一
startOfWeek.setDate(now.getDate() - diff);
startOfWeek.setHours(0, 0, 0, 0); // 设置为本周一的00:00:00
// 时间快捷键
const presets = reactive({
	今天: [new Date(), new Date()],
	昨天: [new Date(+new Date() - 86400000), new Date(+new Date() - 86400000)],
	本周: [startOfWeek, new Date()],
	本月: [new Date(new Date().getFullYear(), now.getMonth(), 1, 0, 0, 0, 0), new Date()],
	近7天: [new Date(+new Date() - 86400000 * 6), new Date()],
	近30天: [new Date(+new Date() - 86400000 * 29), new Date()]
});
const disDate = ref({
	before: new Date(+new Date() - 86400000 * 47),
	after: new Date(+new Date() + 86400000 * 46)
});

// 表单校验
const FORM_RULES = {
	mobilephonenum: [
		{ required: true, message: '请输入手机号码' },
		{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'change' }
	],
	calloutnum: [
		{
			validator: (val, value, callback) => {
				console.log(val, '========>val');
				const regex = /^[1-9]$/;
				if (val[0] == '' || val[1] == '' || val.length < 2) {
					return false;
				} else if (!regex.test(val[0]) || !regex.test(val[1])) {
					// console.log(regex.test(val[0]),'========>regex.test(val[0])');
					return false;
				} else {
					return true;
				}
			},
			message: '请输入1~9的外呼次数',
			trigger: 'change'
		}
	],
	provinceaff: [{ required: true, message: '请选择归属地（省）', trigger: 'change' }],
	cityaff: [{ required: true, message: '请选择归属地（市）', trigger: 'change' }],
	categories: [{ required: true, message: '请选择类别', trigger: 'change' }],
	operator: [{ required: true, message: '请选择供应商', trigger: 'change' }],
	timing: [{ required: true, message: '请选择启动时间段' }],
	bells: [
		{ required: true, message: '请输入最长振铃时间(5s-60s)' },
		{ pattern: /^([5-9]|[1-5][0-9]|60)$/, message: '请输入5s-60s正整数', trigger: 'change' }
	]
};

const onMinCallChange = (val) => {
	formData.calloutnum[0] = val;
	console.log(formData.calloutnum, '========>val');
};
const onMaxCallChange = (val) => {
	formData.calloutnum[1] = val;
	console.log(formData.calloutnum, '========>val');
};




</script>

<style lang="scss" scoped>
.formBox {
  padding: 20px;
}
:deep(.t-form-inline .t-form__item) {
  min-width: 60px !important;
}
:deep(.t-pagination .t-pagination__select) {
  position: relative;
  height: 28px !important;
}
.topbuttons{
	display: flex;
	.dk-button {
		margin-left: 10px;
	}
}
</style>
